<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketTest</title>
</head>
<body>
<div class="div1">
    <input/>
    <button class="btn1">发送消息</button>
    <button class="btn2">关闭连接</button>
</div>
<div class="div2"></div>
<script>
    let ws = null;

    if ("WebSocket" in window) {
        const cid = Math.random().toString(36).substring(2);
        ws = new WebSocket("ws://localhost:8083/ws/" + cid);
        const div2 = document.querySelector(".div2");
        const btn1 = document.querySelector(".btn1");
        const btn2 = document.querySelector(".btn2");

        btn1.onclick = function () {
            const input = document.querySelector("input");
            const msg = input.value;
            ws.send(msg);
        }

        btn2.onclick = function () {
            ws.close();
        }

        ws.onopen = function (...p) {
            console.log("连接成功", p)
            div2.innerHTML = "连接成功"
        }

        ws.onclose = function (e) {
            console.log("关闭连接", e, ws.readyState)
            if (e.wasClean) {
                div2.innerHTML = "正常关闭"
            } else {
                div2.innerHTML = "异常关闭"
            }
        }

        ws.onerror = function (...p) {
            console.log("错误", p)
            div2.innerHTML = "错误"
        }

        ws.onmessage = function (e) {
            console.log("收到消息", e.data)
            const p = document.createElement("p");
            p.innerHTML = e.data;
            div2.appendChild(p);
        }
    }
</script>
</body>
</html>